<template>
    <div>
        <div class="echarts-wrap" ref="echartWord"></div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, ref, onBeforeUnmount, onUpdated, nextTick } from 'vue'
import 'echarts-wordcloud'

const props = defineProps({
    //词云数据
    data: {
        type: Array,
        required: true,
    },
    shape: {
        type: String,
        default: 'square',
    },
});

const echartWord = ref(null);
let myChart = null;

const initChart = async () => {
    await nextTick(); // 等待 DOM 更新
    if (echartWord.value) {
        if (myChart) {
            myChart.dispose(); // 如果图表已经存在，先销毁
        }
        myChart = echarts.init(echartWord.value);
        const option = {
            series: [{
                type: 'wordCloud',
                shape: props.shape,
                rotationRange: [0, 0],
                gridSize: 8,
                sizeRange: [16, 72],
                layoutAnimation: true, 
                rotationStep: 45,
                textStyle: {
                    fontFamily: 'sans-serif',
                    fontWeight: 'bold',
                    color: function () {
                        const hue = Math.floor(Math.random() * 360);
                        return `hsl(${hue}, 80%,75%)`;
                    },
                },
                emphasis: {
                    shadowBlur: 10,
                    shadowColor: '#333'
                },
                // 设置词云数据
                data: props.data
            }]
        };
        myChart.setOption(option);
        window.addEventListener('resize', myChart.resize);
    }
};

onMounted(() => {
    initChart();
});

onBeforeUnmount(() => {
    if (myChart) {
        window.removeEventListener('resize', myChart.resize);
        myChart.dispose();
    }
});

onUpdated(() => {
    initChart();
});
</script>

<style scoped>
.echarts-wrap {
    width: 100%;
    height: 400px;
    min-width: 400px;
}
</style>